---
title: ""
output: pdf_document
geometry: "top=1in, bottom=1in, left=1in, right=1in"
header-includes:
    - \usepackage{caption}
    - \usepackage{lscape}
---

\newcommand{\blandscape}{\begin{landscape}}
\newcommand{\elandscape}{\end{landscape}}

\captionsetup[table]{labelformat=empty}


```{r setup, include=FALSE, message=FALSE}

# Package setup
if (!require("pacman")) install.packages("pacman", repos = "http://cran.us.r-project.org"); library(pacman);
pacman::p_load(yaml, arrow, readr, tidyr, glue, argparse, here, purrr, stringr, dplyr, knitr, kableExtra, stats);

# Working directory and command line argument setup
current_script = "generate_tables_and_figures/gen_takeup_model_outputs/src/gen_takeup_model_outputs.Rmd"
here::i_am(current_script)
source(here("R", "project_functions.R"))
task_dir = here(dirname(dirname(file.path(current_script))))
knitr::opts_knit$set(root.dir = task_dir)
cl_args <- parse_make_args(c(
  "RMD_FILE",
  "TAKEUP_RESULTS",
  "HOURS_WORKED_RESULTS",
  "CONFIG_FILE",
  "OUTCOME_LABELS_FILE",
  "TABLE_CONFIG",
  "OUT_DIR"
), inter_active = TRUE, task_dir = task_dir)

knitr_setup()
  
```


```{r}

config <- read_yaml(cl_args$CONFIG_FILE)

ylabels <- read_csv(cl_args$OUTCOME_LABELS_FILE, show_col_types = F) %>%
  rename(term = value)

table_config <- read_yaml(cl_args$TABLE_CONFIG)
source('../R/table_functions.R')

beta_se_digits <- table_config$digits$beta_se

baseline_vars <- tibble(
  term = c(config$baseline_demos_varlist, 
           config$baseline_outcomes_varlist, 
           config$baseline_uphat_varlist,
           config$baseline_arrests_varlist, 
           config$baseline_vics_varlist,
           config$baseline_incar_varlist,
           config$baseline_nbhood_varlist,
           config$baseline_pathway_varlist)) %>%
  mutate(order = row_number())

add_baseline_group_rows <- function(kable) {
  kable %>%
    group_rows("Demographics", 2, 3) %>%
    group_rows("Primary Outcome Components", 4, 6) %>%
    group_rows("Risk Prediction", 7, 8) %>%
    group_rows("Arrest Counts", 9, 12) %>%
    group_rows("Victimization Counts", 13, 14) %>%
    group_rows("Incarceration Measures", 15, 16) %>%
    group_rows("Neighborhood", 17, 18) %>%
    group_rows("Pathway", 19, 20)
}

```

\blandscape

```{r}

results <- bind_rows(
  read_csv(cl_args$TAKEUP_RESULTS, show_col_types = F),
  read_csv(cl_args$HOURS_WORKED_RESULTS, show_col_types = F)) %>%
  filter(covariate_set %in% names(config$covariate_sets),
         outcome %in% names(config$outcome_sets),
         subgroup == config$subgroup,
         window == config$window) %>%
  mutate(term = gsub('_pre$', '', term)) %>%
  left_join(baseline_vars, by = 'term') %>%
  left_join(ylabels %>% select(term, label), by = 'term') %>%
  select(-term) %>% rename(term = label) %>%
  # shorten one label
  mutate(term = case_when(term == 'Other (Non-Shooting) Violent Victimizations' ~ "Non-Shooting Violent Victimizations",
                          TRUE ~ term)) %>%
  mutate(term = case_when(term == 'ULRA Risk Score (Zero-Imputed)' ~ "Risk Score (Zero-Imputed)",
                          TRUE ~ term)) %>%
  mutate(term = case_when(term %in% config$non_std_columns ~ term,
                          TRUE ~ paste(term, '(std.)')),
         n = as.character(n),
         beta = case_when(grepl('hours', outcome) ~ fmt(beta, decimals = 1),
                          TRUE ~ fmt(beta, decimals = 3)),
         beta = paste0(beta, replace_na(istar, '')),
         adj_r2 = fmt(adj_r2, decimals = 3),
         treatment_mean = case_when(grepl('hours', outcome) ~ fmt(treatment_mean, decimals = 1),
                          TRUE ~ fmt(treatment_mean, decimals = 3)))

results <- bind_rows(

    results %>%
    select(outcome, covariate_set, n) %>%
    mutate(term = 'N', 
           order = -1) %>%
    rename(beta = n) %>%
    distinct(),

  results %>%
    select(outcome, order, covariate_set, term, beta),
  
  results %>%
    select(outcome, covariate_set, adj_r2) %>%
    mutate(term = 'Adjusted R-squared', 
           order = 999) %>%
    rename(beta = adj_r2) %>%
    distinct(),

  results %>%
    select(outcome, covariate_set, treatment_mean) %>%
    mutate(term = 'D.V. Mean', 
           order = 999) %>%
    rename(beta = treatment_mean) %>%
    distinct())

covariate_set_list = unlist(config$covariate_sets)
outcome_set_list = unlist(config$outcome_sets)
results <- results %>%
  mutate(covariate_set = covariate_set_list[match(covariate_set, names(covariate_set_list))],
         outcome = outcome_set_list[match(outcome, names(outcome_set_list))])

desired_column_order <- expand.grid(unname(covariate_set_list), unname(outcome_set_list)) %>%
  mutate(order = paste(Var2, Var1,  sep = '__')) %>%
  pull(order)
  
results_wide <- results %>%
  pivot_wider(names_from = outcome, values_from = beta) %>%
  pivot_wider(names_from = covariate_set, values_from = all_of(unique(results$outcome)), names_sep = '__') %>%
  arrange(order) %>%
  select(term, all_of(desired_column_order))

#header = as.list(c(1, rep(length(covariate_set_list), length(outcome_set_list))))
#names(header) = c(' ', gsub('_', ' ', unname(outcome_set_list)))
#colnames = c(" ", rep(unname(covariate_set_list), length(outcome_set_list)))
#colnames = gsub('_', ' ', colnames)

colnames = c(' ', sapply(strsplit(desired_column_order, split = '__'), '[[', 1))
colnames = gsub('_', ' ', colnames)

table <- results_wide %>% 
  kable(booktabs = table_config$booktabs, 
        longtable = table_config$longtable,
        col.names = colnames,
        align = c(table_config$alignment$text, 
                  rep(table_config$alignment$numeric, 
                      length(colnames) - 1)),
        linesep = '') %>% 
  kable_styling(font_size = 11) %>%
  #add_header_above(header) %>%
  add_baseline_group_rows() %>%
  column_spec(1, width="21em", latex_valign = "b") %>%
  column_spec(2:9, width="4.8em", latex_valign = "b") %>%
  row_spec(nrow(results_wide)-2, hline_after = T) %>%
  add_indent(1)

table

# SAVE

timestamp <- get_timestamp()
writeLines(table, glue(cl_args$OUT_DIR, "/takeup_model_up_to_date.tex"))
writeLines(table, glue(cl_args$OUT_DIR, "/takeup_model_{timestamp}.tex"))

```

\elandscape

